#include "dlgimupara.h"
#include "ui_dlgimupara.h"
#include <QDebug>
#include <QInputDialog>

#include <yaml-cpp/yaml.h>
#include <fstream>
#include <iostream>

#include <../mainwindow.h>
#include <QComboBox>
#include <QMessageBox>


DlgIMUPara::DlgIMUPara(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DlgIMUPara)
{
    ui->setupUi(this);
    ui->tableWidget_laser->setEditTriggers(QTableWidget::NoEditTriggers);
    ui->lineEdit_fromID->setEnabled(false);
    slot_loadAmrYAML();
}

DlgIMUPara::~DlgIMUPara()
{
    delete ui;
}

void DlgIMUPara::slot_loadAmrYAML()
{
    try {
        for(int i=ui->tableWidget_laser->rowCount()-1;i>=0;i--)
            ui->tableWidget_laser->removeRow(i);
        YAML::Node config = YAML::LoadFile(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        QStringList m_laserIDList = QString::fromStdString(config[m_equipmentType+"_IDList"].as<std::string>()).split(",",Qt::SkipEmptyParts);
        qDebug()<<"DlgIMUPara::slot_loadAmrYAML()="<<m_laserIDList;
        for(int i=0;i<m_laserIDList.length();i++)
        {
            int row = ui->tableWidget_laser->rowCount();
            ui->tableWidget_laser->insertRow(row);
            ui->tableWidget_laser->setItem(row,0,new QTableWidgetItem(QString(m_laserIDList[i])));
        }
        slot_updateFrameIDData(ui->lineEdit_fromID->text());
    } catch (const std::exception& e) {
        qDebug()<< "处理YAML文件时发生错误: " << e.what();
    }
}

void DlgIMUPara::slot_updateFrameIDData(QString laserID)
{
    try {
        YAML::Node config = YAML::LoadFile(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        ui->lineEdit_fromID->setText(QString::fromStdString(config[laserID.toStdString()]["frame_id"].as<std::string>()));
        ui->checkBox_Enabledevice->setChecked(config[laserID.toStdString()]["Enabledevice"].as<bool>());
        ui->dSBox_laserX->setValue(config[laserID.toStdString()]["x"].as<double>());
        ui->dSBox_laserY->setValue(config[laserID.toStdString()]["y"].as<double>());
        ui->dSBox_laserZ->setValue(config[laserID.toStdString()]["z"].as<double>());
        ui->dSBox_laserYaw->setValue(config[laserID.toStdString()]["yaw"].as<double>());
        ui->dSBox_laserMinAngle->setValue(config[laserID.toStdString()]["minAngle"].as<double>());
        ui->dSBox_laserMaxAngle->setValue(config[laserID.toStdString()]["maxAngle"].as<double>());
        ui->dSBox_minRange->setValue(config[laserID.toStdString()]["minRange"].as<double>());
        ui->dSBox_maxRange->setValue(config[laserID.toStdString()]["maxRange"].as<double>());
        ui->lineEdit_lasrIP->setText(QString::fromStdString(config[laserID.toStdString()]["device_ip"].as<std::string>()));
        ui->spBox_laserPort->setValue(config[laserID.toStdString()]["device_port"].as<double>());
    } catch (const std::exception& e) {
        qDebug()<< "处理YAML文件时发生错误: " << e.what();
    }
}

void DlgIMUPara::setParent(void *parent)
{
    m_parent = parent;
}

void DlgIMUPara::slot_AddorDelete()
{
    try {
        qDebug()<<"m_laserIDList-------------------1";
        YAML::Node config = YAML::LoadFile(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        qDebug()<<"m_laserIDList-------------------2";
        if(config[m_equipmentType+"_IDList"])
        {
            QStringList m_laserIDList = QString::fromStdString(config[m_equipmentType+"_IDList"].as<std::string>()).split(",",Qt::SkipEmptyParts);
            qDebug()<<"m_laserIDList-------------------"<<m_laserIDList;
            for(int i=0;i<m_laserIDList.length();i++)
            {
                bool is_Have = false;
                for(int row=0;row<ui->tableWidget_laser->rowCount();row++)
                {
                    if(ui->tableWidget_laser->item(row,0)->text() == QString(m_laserIDList[i]))
                    {
                        is_Have = true;
                        break;
                    }
                }
                if(!is_Have)
                {
                    config.remove(QString(m_laserIDList[i]).toStdString());
                }
            }
        }
        QString ssssssssList;
        for(int row=0;row<ui->tableWidget_laser->rowCount();row++)
        {
            ssssssssList.append(ui->tableWidget_laser->item(row,0)->text()+",");
        }
        qDebug()<<"sssssssssssssssssssssssssssList="<<ssssssssList;
        config[m_equipmentType+"_IDList"] = ssssssssList.toStdString();
        // 保存修改到YAML文件
        std::ofstream fout(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        fout << config;
        fout.close();

    } catch (const std::exception& e) {
        qDebug()<< "处理YAML文件时发生错误: " << e.what();
    }
}

void DlgIMUPara::slot_show(QString equipmentType)
{
    m_equipmentType = equipmentType.toStdString();
    ui->label_title->setText(QString(u8"IMU参数设置"));
    slot_loadAmrYAML();
    this->exec();
}

void DlgIMUPara::on_btn_SaveData_clicked()
{
    MainWindow *parent = (MainWindow*)m_parent;
    QMessageBox::StandardButton result = QMessageBox::warning(this,QString(u8"Warning消息框"),QString(u8"是否修改设备参数并推送"),
                                                              QMessageBox::Ok|QMessageBox::Discard,
                                                              QMessageBox::Ok);
    if(result == QMessageBox::Ok)
    {
        try {
            YAML::Node config = YAML::LoadFile(g_LocalMapPath.toStdString() +"/PLNS.yaml");
            QString laserID = ui->lineEdit_fromID->text();
            config[laserID.toStdString()]["frame_id"] = ui->lineEdit_fromID->text().toStdString();
            config[laserID.toStdString()]["Enabledevice"] = ui->checkBox_Enabledevice->isCheckable();
            config[laserID.toStdString()]["x"] = ui->dSBox_laserX->value();
            config[laserID.toStdString()]["y"] = ui->dSBox_laserY->value();
            config[laserID.toStdString()]["z"] = ui->dSBox_laserZ->value();
            config[laserID.toStdString()]["yaw"] = ui->dSBox_laserYaw->value();
            config[laserID.toStdString()]["minAngle"] = ui->dSBox_laserMinAngle->value();
            config[laserID.toStdString()]["maxAngle"] = ui->dSBox_laserMaxAngle->value();
            config[laserID.toStdString()]["minRange"] = ui->dSBox_minRange->value();
            config[laserID.toStdString()]["maxRange"] = ui->dSBox_maxRange->value();
            config[laserID.toStdString()]["device_ip"] = ui->lineEdit_lasrIP->text().toStdString();
            config[laserID.toStdString()]["device_port"] = ui->spBox_laserPort->value();
            // 保存修改到YAML文件
            std::ofstream fout(g_LocalMapPath.toStdString() +"/PLNS.yaml");
            fout << config;
            fout.close();
            parent->m_TMSSHConnectWGT->Public_ssh_PushFilePath("/PLNS.yaml");
        } catch (const std::exception& e) {
            qDebug()<< "处理YAML文件时发生错误: " << e.what();
        }
    }
    else
    {
        slot_loadAmrYAML();
    }
}


void DlgIMUPara::on_btn_laserAdd_clicked()
{
    QString text = QInputDialog::getText(
        this, // 父窗口指针
        "add Device", // 标题
        "请输入设备名称(fram_id):", // 提示
        QLineEdit::Normal, // 输入框类型
        "" // 默认文本
        );

    // 检查用户是否点击了取消
    if (text.isNull()) {
        // 用户点击了取消
    } else {
        // 用户输入了文本，text变量包含输入的内容
        int row = ui->tableWidget_laser->rowCount();
        for(int j=0;j<row;j++)
        {
            if(ui->tableWidget_laser->item(j,0)->text() == text)
            {
                return;
            }
        }
        ui->tableWidget_laser->insertRow(row);
        ui->tableWidget_laser->setItem(row,0,new QTableWidgetItem(text));
        slot_AddorDelete();

    }
    // QMessageBox::StandardButton result = QMessageBox::warning(this,QString(u8"Warning消息框"),QString(u8"添加设备"),
    //                                                           QMessageBox::Ok|QMessageBox::Discard,
    //                                                           QMessageBox::Ok);
    // if(result == QMessageBox::Discard)
    //     return;

    // int laserid = -1;
    // int row = ui->tableWidget_laser->rowCount();
    // for(int i=0;i<10;i++)
    // {
    //     bool is_Have = false;
    //     for(int j=0;j<row;j++)
    //     {
    //         if(ui->tableWidget_laser->item(j,0)->text() == QString::fromStdString(m_equipmentType)+QString::number(i))
    //         {
    //             is_Have = true;
    //             break;
    //         }
    //     }
    //     if(!is_Have)
    //     {
    //         laserid = i;
    //         break;
    //     }
    // }
    // if(laserid>-1)
    // {
    //     ui->tableWidget_laser->insertRow(row);
    //     ui->tableWidget_laser->setItem(row,0,new QTableWidgetItem(QString::fromStdString(m_equipmentType)+QString::number(laserid)));
    //     slot_AddorDelete();
    // }
}

void DlgIMUPara::on_btn_laserDel_clicked()
{
    if(ui->tableWidget_laser->currentIndex().row() < 0)
        return;
    QMessageBox::StandardButton result = QMessageBox::warning(this,QString(u8"Warning消息框"),
                                                              QString(u8"是否删除设备:%1").arg(ui->tableWidget_laser->item(ui->tableWidget_laser->currentIndex().row(),0)->text()),
                                                              QMessageBox::Ok|QMessageBox::Discard,
                                                              QMessageBox::Ok);
    if(result == QMessageBox::Discard)
        return;
    ui->tableWidget_laser->removeRow(ui->tableWidget_laser->currentIndex().row());
    slot_AddorDelete();
}


void DlgIMUPara::on_tableWidget_laser_doubleClicked(const QModelIndex &index)
{
    QString data = ui->tableWidget_laser->item(index.row(),0)->text();
    ui->lineEdit_fromID->setText(data);
    slot_updateFrameIDData(data);
}


